package filenavigation

import (
	"fmt"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/os/glog"
	"gitlab.local/DO-module/new-filemanage-module/src/constant"
	"gitlab.local/golibrary/linux"
	"gitlab.local/golibrary/utils"
	"golang.org/x/sys/unix"
	"os"
	"path/filepath"
	"time"
)

type Level uint8
type Tag string

// log level
const (
	Debug Level = iota
	Info
	Notice
	Warn
	Err
	Crit
	Alert
	Emerg
)

const (
	LogFormat     = "%d|%s|%s|%s|%s|%d|%s|%s\n" //日志格式(秒级时间戳|应用名称|本机ip|设备名称|用户|日志等级|标签|信息)
	HttpTag   Tag = "http"
)

// RecordedLog 记入日志
// lv 日志等级
// user 用户名称
// tag 标记
// msg 信息
// remoteIp 远程ip
func (n *FileNav) RecordedLog(lv Level, user string, tag Tag, msg, remoteIp string) {
	go func() {
		if e := utils.SwitchUserRight(); e != nil {
			glog.Warning("RecordedLog", e)
			return
		}
		conf, err := n.GetRecentlyConf(user)
		if err != nil {
			glog.Warning(err, "RecordedLog")
			return
		}
		if conf.LogIn {
			_ = n.log(lv, user, tag, msg, remoteIp)
		}
	}()
}

// log 日志保存
func (n *FileNav) log(lv Level, user string, tag Tag, msg, remoteIp string) error {
	hostname, err := os.Hostname() //设备名称
	if err != nil {
		glog.Warning(err, "log")
	}
	logPath := fmt.Sprintf(constant.FileManagerLog, linux.GetMainVolume())
	if err = os.MkdirAll(logPath, 0700); err != nil {
		return err
	}
	src := filepath.Join(logPath, time.Now().Format("2006-01-02")) //以天保存
	if !utils.Exists(src) {
		create, err := os.Create(src) //创建文件
		if err != nil {
			return gerror.Wrap(err, "log1")
		}
		_ = create.Close()
		_ = os.Chmod(src, 0666)
	}
	file, err := os.OpenFile(src, os.O_WRONLY|os.O_APPEND, os.ModePerm)
	if err != nil {
		return gerror.Wrap(err, "log2")
	}
	defer file.Close()
	_ = unix.Flock(int(file.Fd()), unix.LOCK_EX)
	if _, err = file.WriteString(fmt.Sprintf(LogFormat, time.Now().Unix(), "filemanager", remoteIp, hostname, user, lv, tag, msg)); err != nil {
		return gerror.Wrap(err, "log3")
	}
	return nil
}
